package com.jt.friendsmanagement;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class FriendsListFragment extends Fragment {
    private RecyclerView mFriendsRecyclerView; //recyclerView
    private FriendAdapter mFriendAdapter;

    private boolean mSubtitleVisible;
    public static final String[] constellationArr = {"水瓶座", "双鱼座", "白羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座", "魔羯座"};


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_friends_list, container, false);
        mFriendsRecyclerView = (RecyclerView) view.findViewById(R.id.friends_recycler_view);
        mFriendsRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        updateUI();
        mFriendsRecyclerView.setOnCreateContextMenuListener(
                new View.OnCreateContextMenuListener() {
                    @Override
                    public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
                        contextMenu.add(0,1,0,"修改");
                        contextMenu.add(0,2,0,"删除");
                    }
                }
        );
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        updateUI();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.new_friend:
                Friend friend = new Friend();
                FriendLab.get(getActivity()).addFriend(friend);
                Intent intent = AddFriendActivity.newIntent(getActivity(), friend.getId());
                startActivity(intent);
                return true;
            case R.id.show_subtitle:
                mSubtitleVisible =!mSubtitleVisible;
                getActivity().invalidateOptionsMenu();
                updateSubtitle();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }

    }

    private void updateSubtitle() {
        FriendLab friendLab = FriendLab.get(getActivity());
        int friendCount = friendLab.getFriends().size();
        String subtitle = getString(R.string.subtitle_format, friendCount);
        if (!mSubtitleVisible) {
            subtitle = null;
        }

        AppCompatActivity activity = (AppCompatActivity) getActivity();
        activity.getSupportActionBar().setSubtitle(subtitle);
    }
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.fragment_friends_list,menu);
        /*点击show subtitle时更新子标题*/
        MenuItem subtitleItem = menu.findItem(R.id.show_subtitle);
        if (mSubtitleVisible) {
            subtitleItem.setTitle("取消显示");
        } else {
            subtitleItem.setTitle("显示朋友数");
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0,1,0,"修改");
        menu.add(0,2,0,"删除");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        //Toast.makeText(MainActivity.this,String.valueOf(mAdapter.mPosition),Toast.LENGTH_SHORT).show();

        switch (item.getItemId()){
            case 1:
                Intent intent = AddFriendActivity.newIntent(getActivity(), FriendLab.get(getActivity()).getFriends().get(mFriendAdapter.getPosition()).getId());
                startActivity(intent);
                break;
            case 2:
                FriendLab.get(getActivity()).getFriends().remove(mFriendAdapter.getPosition());
                mFriendAdapter.notifyItemRemoved(mFriendAdapter.mPosition);
                break;
        }

        return super.onContextItemSelected(item);
    }

    /*定义ViewHolder内部类和Adapter*/
    private class FriendHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        private TextView mName;
        private TextView mSex;
        private TextView mAge;
        private TextView mConstellation;
        private TextView mHobby1;
        private TextView mHobby2;
        private TextView mHobby3;

        private Friend mFriend; //要在bind方法中使用，setText

        public void bind(Friend friend) {
            mFriend = friend;
            mName.setText(friend.getName());
            mSex.setText(friend.getSex());

            /*年龄计算*/
            int age, year_now;
            Calendar fromCalendar = Calendar.getInstance();
            fromCalendar.setTime(new Date());
            year_now = fromCalendar.get(Calendar.YEAR);
            fromCalendar.setTime(mFriend.getBirthday());
            age = year_now - fromCalendar.get(Calendar.YEAR);
            mAge.setText(String.valueOf(age));

            mConstellation.setText(getConstellation(constellationArr, fromCalendar.get(Calendar.MONTH), fromCalendar.get(Calendar.DAY_OF_MONTH)));

            String hobbies[] = mFriend.getHobbies();
            if (hobbies.length>0) mHobby1.setText(mFriend.getHobbies()[0]);
            if (hobbies.length>1) mHobby2.setText(mFriend.getHobbies()[1]);
            if (hobbies.length>2)  mHobby3.setText(mFriend.getHobbies()[2]);
        }


        /*这里传入的inflater和ViewGroup是什么意思？*/
        public FriendHolder(LayoutInflater inflater, ViewGroup parent) {
            super(inflater.inflate(R.layout.list_item_friend, parent, false));
            itemView.setOnClickListener(this);
            /*每次有新的friend项要在列表中显示，都会调用bind(Friend)方法*/
            /*在构造方法中实例化组件*/
            mName = (TextView) itemView.findViewById(R.id.friend_name);
            mSex = (TextView) itemView.findViewById(R.id.friend_sex);
            mAge = (TextView) itemView.findViewById(R.id.friend_age);
            mConstellation = (TextView) itemView.findViewById(R.id.friend_constellation);
            mHobby1 = (TextView) itemView.findViewById(R.id.friend_hobby1);
            mHobby2 = (TextView) itemView.findViewById(R.id.friend_hobby2);
            mHobby3 = (TextView) itemView.findViewById(R.id.friend_hobby3);
        }

        @Override
        public void onClick(View view) {
            /*点击一项viewItem时唤醒addFriendActivity,传入friendId*/
            Intent intent = AddFriendActivity.newIntent(getActivity(), mFriend.getId());
            startActivity(intent);
        }
    }

    /*创建Adapter*/
    private class FriendAdapter extends RecyclerView.Adapter<FriendHolder> {
        private List<Friend> mFriends;

        public int getPosition() {
            return mPosition;
        }

        private int mPosition;

        public FriendAdapter(List<Friend> friends) {
            mFriends = friends;
        }

        @NonNull
        @Override
        public FriendHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
            return new FriendHolder(layoutInflater, viewGroup);
        }

        @Override
        public void onBindViewHolder(@NonNull final FriendHolder friendHolder, int i) {
            /*在这里调用bind()方法，就可以设定列表项的内容了*/
            Friend friend = mFriends.get(i);
            friendHolder.bind(friend);
            friendHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    mPosition = friendHolder.getAdapterPosition();
                    return false;
                }
            });
        }

        @Override
        public int getItemCount() {
            return mFriends.size();
        }
    }

    private void updateUI() {
        FriendLab friendLab = FriendLab.get(getActivity());
        List<Friend> friends = friendLab.getFriends();

        if (mFriendAdapter == null) {
            mFriendAdapter = new FriendAdapter(friends);
            mFriendsRecyclerView.setAdapter(mFriendAdapter);
        } else {
            mFriendAdapter.notifyDataSetChanged();
        }
    }

    //contellationArr 星座的数组
    //month 月份
    //day  日

    public static String getConstellation(String[] contellationArr, int month, int day) {
        int point = -1;
        Double date = Double.parseDouble(month + "." + day);
        if (3.21 <= date && 4.19 >= date) {
            point = 0;
        } else if (4.20 <= date && 5.20 >= date) {
            point = 1;
        } else if (5.21 <= date && 6.21 >= date) {
            point = 2;
        } else if (6.22 <= date && 7.22 >= date) {
            point = 3;
        } else if (7.23 <= date && 8.22 >= date) {
            point = 4;
        } else if (8.23 <= date && 9.22 >= date) {
            point = 5;
        } else if (9.23 <= date && 10.23 >= date) {
            point = 6;
        } else if (10.24 <= date && 11.22 >= date) {
            point = 7;
        } else if (11.23 <= date && 12.21 >= date) {
            point = 8;
        } else if (12.22 <= date && 12.31 >= date) {
            point = 9;
        } else if (1.01 <= date && 1.19 >= date) {
            point = 9;
        } else if (1.20 <= date && 2.18 >= date) {
            point = 10;
        } else if (2.19 <= date && 3.20 >= date) {
            point = 11;
        }
        if (point == -1) {
            return contellationArr[2];
        }
        return contellationArr[point];
    }

}
